<?php
/**
 * Created by PhpStorm.
 * User: Neho
 * Date: 2017/11/15
 * Time: 20:45
 */


namespace app\api\logic;

use think\Model;
use app\common\model\Auth as AuthModel;
use app\common\model\User as UserModel;

class User extends Model
{

    //用户携带微信code登录
    public function login()
    {
        if (request()->param("code")) {
            //请求中携带code字段
            $WxService = \think\Loader::model('Wx', 'service');
            $weixinCode = request()->param("code");
            $userAccessToken = $WxService->getUserAccessToken($weixinCode);
            $objUserAccessToken = json_decode($userAccessToken);
            if (isset($objUserAccessToken->access_token)) {
                //正确获取用户access_code
                $userInfo = $WxService->getUserInfo($objUserAccessToken->access_token, $objUserAccessToken->openid);
                $objUserInfo = json_decode($userInfo);
                if (isset($objUserInfo->openid)) {
                    //正确获取用户信息
                    //实例化模型
                    $user = new UserModel;
                    $auth = new AuthModel;
                    $existAuth = AuthModel::getByAuthAccount($objUserInfo->openid);
                    //是否用户信息已经录入数据库
                    if (isset($existAuth)) {
                        //已经存在用户数组
                        $exitUser = UserModel::hasWhere('Auth', ['auth_account' => $existAuth->auth_account])->select();
                        //返回用户id
                        $data = array(
                            'userId' => $exitUser[0]->user_id
                        );
                        return $data;
                    } else {
                        //不存在
                        //将微信获取的必要用户信息保存到数据库中
                        //开启事务
                        $this->startTrans();
                        try {
                            //数据库多表操作
                            //新增user表
                            $user->user_nick_name = $objUserInfo->nickname;
                            $user->user_avatar = $objUserInfo->headimgurl;
                            //user表新增成功
                            if ($user->save()) {
                                //将授权验证信息写入auth表
                                $auth->auth_account = $objUserAccessToken->openid;
                                $auth->auth_token_1 = $objUserAccessToken->access_token;
                                $auth->auth_token_2 = $objUserAccessToken->refresh_token;
                                $auth->auth_type = 1;
                                $user->Auth()->save($auth);
                            } else {
                                //user表写入失败
                                return $user->getError();
                            }
                            // 提交事务
                            $this->commit();
                            //关联表写入成功
                            $data = array(
                                'userId' => $user->user_id
                            );
                            return $data;
                        } catch (\Exception $e) {
                            // 回滚事务
                            $this->rollback();
                        }
                    }
                } else {
                    //获取用户信息失败
                }
            } else {
                //获取用户access_code失败
            }
        } else {
            //请求体中没有携带需要的code字段
        }
    }

    //根据请求头携带的token获取相应的用户数据
    public function getUserInfo($user_id)
    {
        if (isset($user_id)) {
            //User控制器传入了用户id
            $user = UserModel::getByUserId($user_id);
            if (isset($user->user_nick_name)) {
                //用户id可以在数据库中查找到对应的信息
                $data = array(
                    'nickName' => $user->user_nick_name,
                    'userAvatar' => $user->user_avatar,
                    'realName' => $user->user_real_name
                );
                return $data;
            } else {
                //查找信息失败
            }
        } else {
            //$user为非法值
        }
    }
}
